package org.dromara.hrp.service.impl;

import cn.hutool.core.date.DateTime;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.RequiredArgsConstructor;
import org.dromara.common.core.domain.R;
import org.dromara.common.core.utils.MapstructUtils;
import org.dromara.common.core.utils.StringUtils;
import org.dromara.common.mybatis.core.page.PageQuery;
import org.dromara.common.mybatis.core.page.TableDataInfo;
import org.dromara.common.web.core.BaseService;
import org.dromara.fms.service.impl.FmsBillServiceImpl;
import org.dromara.hrp.domain.HrpLead;
import org.dromara.hrp.domain.HrpLeadComment;
import org.dromara.hrp.domain.HrpLeadQuote;
import org.dromara.hrp.mapper.HrpLeadCommentMapper;
import org.dromara.hrp.mapper.HrpLeadMapper;
import org.dromara.hrp.mapper.HrpLeadQuoteMapper;
import org.dromara.system.domain.vo.SysPostVo;
import org.dromara.system.service.impl.SysPostServiceImpl;
import org.dromara.wms.domain.WmsOrder;
import org.dromara.wms.domain.WmsOrderLine;
import org.dromara.wms.domain.WmsProduct;
import org.dromara.wms.mapper.WmsOrderMapper;
import org.dromara.wms.mapper.WmsProductMapper;
import org.dromara.wms.service.WmsOrderServiceImpl;
import org.dromara.wms.service.WmsStockService;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;

/**
 * 线索商机Service业务层处理
 *
 * @author wenrui
 * @date 2024-03-21
 */
@RequiredArgsConstructor
@Service
public class HrpLeadServiceImpl extends BaseService {

  private final HrpLeadMapper baseMapper;
  private final HrpLeadQuoteMapper quoteMapper;
  private final HrpLeadCommentMapper commentMapper;
  private final SysPostServiceImpl sysPostService;
  private final WmsOrderServiceImpl wmsOrderService;
  private final WmsProductMapper wmsProductMapper;
  private final WmsOrderMapper wmsOrderMapper;
  private final FmsBillServiceImpl fmsBillService;

  /**
   * 获取所有主表数据
   */
  public List<HrpLead> list() {
    List<HrpLead> list = baseMapper.selectList();
    return MapstructUtils.convert(list, HrpLead.class);
  }

  /**
   * 查询线索商机
   */
  public HrpLead queryById(Long id) {
    return baseMapper.getHrpLead(id);
  }

  /**
   * 查询线索商机列表
   */
  public TableDataInfo<HrpLead> queryPageList(HrpLead bo, PageQuery pageQuery) {
    Page<HrpLead> result = baseMapper.getHrpLeadList(pageQuery.build(),bo);
    return TableDataInfo.build(result);
  }

  /**
   * 查询线索商机列表
   */
  public List<HrpLead> queryList(HrpLead bo) {
    LambdaQueryWrapper<HrpLead> lqw = buildQueryWrapper(bo);
    return baseMapper.selectList(lqw);
  }

  private LambdaQueryWrapper<HrpLead> buildQueryWrapper(HrpLead bo) {
    Map<String, Object> params = bo.getParams();
    LambdaQueryWrapper<HrpLead> lqw = Wrappers.lambdaQuery();
    lqw.like(StringUtils.isNotBlank(bo.getName()), HrpLead::getName, bo.getName());
    lqw.eq(bo.getPartnerId() != null, HrpLead::getPartnerId, bo.getPartnerId());
    lqw.eq(bo.getSalesId() != null, HrpLead::getSalesId, bo.getSalesId());
    lqw.eq(StringUtils.isNotBlank(bo.getSource()), HrpLead::getSource, bo.getSource());
    lqw.eq(StringUtils.isNotBlank(bo.getStage()), HrpLead::getStage, bo.getStage());
    lqw.eq(StringUtils.isNotBlank(bo.getLostReason()), HrpLead::getLostReason, bo.getLostReason());
    lqw.between(params.get("beginNextTime") != null && params.get("endNextTime") != null,
      HrpLead::getNextTime, params.get("beginNextTime"), params.get("endNextTime"));
    lqw.orderByDesc(params.get("endNextTime") != null, HrpLead::getNextTime);
    return lqw;
  }


  private Boolean checkUserPermissions(Long createBy){
    SysPostVo sysPostVo = sysPostService.selectPostById(createBy);
    return sysPostVo.getIsSales();
  }

  /**
   * 新增线索主从
   */
  @Transactional(propagation = Propagation.REQUIRED)
  public R<Void> insertByBo(HrpLead bo)
  {
    //判断当前用户权限
    if (!checkUserPermissions(bo.getCreateBy())){
      return R.fail("权限不足，无法操作");
    }

    validEntityBeforeSave(bo);
    boolean flag = baseMapper.insert(bo) > 0;

    //新增商机跟踪记录
    this.saveComment(bo);

    return toAjax(flag);
  }



  /**
   * 修改线索主从
   */
  @Transactional(propagation = Propagation.REQUIRED)
  public Boolean updateByBo(HrpLead bo) {

    //判断当前用户权限
    if (!checkUserPermissions(bo.getUpdateBy())){
      return false;
    }

    validEntityBeforeSave(bo);

    //订单明细表
    List<HrpLeadQuote> quoteList = bo.getQuoteList();
    if (quoteList != null && !quoteList.isEmpty()) {
      for (HrpLeadQuote quote : quoteList) {
        if (quote.getQuoteId() == null) {
          quote.setId(bo.getId());
//          quote.setBatchCode("商机订单 "+quote.getId());????批次号不是随便写上去的，没有就默认0
          this.insertQuoteByBo(quote);
        } else {
          this.updateQuoteByBo(quote);
        }
      }
    }

    //新增商机跟踪记录
    this.saveComment(bo);

    return baseMapper.updateById(bo) > 0;
  }

  /**
   * 保存前的数据校验
   */
  private void validEntityBeforeSave(HrpLead entity) {
    //TODO 做一些数据校验,如唯一约束
  }

  /**
   * 批量删除线索主从
   */
  @Transactional(propagation = Propagation.REQUIRED)
  public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
    if (isValid) {
      //TODO 做一些业务上的校验,判断是否需要校验
    }
    this.deleteQuoteWithValidByIds(ids, true);
    return baseMapper.deleteBatchIds(ids) > 0;
  }


  /**
   * 查询线索商机列表
   */
  public TableDataInfo<HrpLeadQuote> queryQuotePageList(HrpLeadQuote bo, PageQuery pageQuery) {
    LambdaQueryWrapper<HrpLeadQuote> lqw = buildQuoteQueryWrapper(bo);
    Page<HrpLeadQuote> result = quoteMapper.selectPage(pageQuery.build(), lqw);
    return TableDataInfo.build(result);
  }

  private LambdaQueryWrapper<HrpLeadQuote> buildQuoteQueryWrapper(HrpLeadQuote bo) {
    LambdaQueryWrapper<HrpLeadQuote> lqw = Wrappers.lambdaQuery();
    lqw.eq(bo.getId() != null, HrpLeadQuote::getId, bo.getId());
    return lqw;
  }

  /**
   * 新增订单
   */
  @Transactional(propagation = Propagation.REQUIRED)
  public Boolean insertQuoteByBo(HrpLeadQuote bo) {
    validLineEntityBeforeSave(bo);
      return quoteMapper.insert(bo) > 0;
  }

  /**
   * 修改订单
   */
  @Transactional(propagation = Propagation.REQUIRED)
  public Boolean updateQuoteByBo(HrpLeadQuote bo) {
    validLineEntityBeforeSave(bo);
    return quoteMapper.updateById(bo) > 0;
  }

  /**
   * 保存前的数据校验
   */
  private void validLineEntityBeforeSave(HrpLeadQuote entity) {
    //TODO 做一些数据校验,如唯一约束
  }


  /**
   * 批量删除通过子表quoteId
   */
  @Transactional(propagation = Propagation.REQUIRED)
  public Boolean deleteWithValidByQuoteIds(Collection<Long> quoteIds, Boolean isValid) {
    if (isValid) {
      //TODO 做一些业务上的校验,判断是否需要校验
    }
    return quoteMapper.deleteBatchIds(quoteIds) > 0;
  }


  /**
   * 通过主表ids删除子表
   */
  @Transactional(propagation = Propagation.REQUIRED)
  public Boolean deleteQuoteWithValidByIds(Collection<Long> ids, Boolean isValid) {
    if (isValid) {
      //TODO 做一些业务上的校验,判断是否需要校验
    }
    LambdaQueryWrapper<HrpLeadQuote> lqw = new LambdaQueryWrapper<>();
    lqw.in(HrpLeadQuote::getId, ids);
    return quoteMapper.delete(lqw) > 0;
  }

  /**
   * 执行
   */
  @Transactional(propagation = Propagation.REQUIRED, rollbackFor = WmsStockService.emptyException.class)
  public R<Void> turnLead(HrpLead lead) throws WmsStockService.emptyException {
    validEntityBeforeSave(lead);
    //获取订单
    List<HrpLeadQuote> hrpLeadQuoteList = this.getQuoteById(lead.getId()).getRows();
    if (hrpLeadQuoteList.isEmpty()){
      throw new WmsStockService.emptyException("空订单，请检查后重试！");
    }
    //订单不为空，分类生成订单
    WmsOrder wmsOrder6 = createOrder(6L,"线索商机-服务订单", lead);
    List<WmsOrderLine> line6 = new ArrayList<>();
    WmsOrder wmsOrder8 = createOrder(8L,"线索商机-库存订单", lead);
    List<WmsOrderLine> line8 = new ArrayList<>();
    hrpLeadQuoteList.forEach(item -> {
      WmsProduct wmsProduct = wmsProductMapper.selectById(item.getProductId());
      if (wmsProduct.getIsStock()){
        //库存商品
        line8.add(this.generateOrder(item));
      }else{
        //服务商品
        line6.add(this.generateOrder(item));
      }
    });
    if (!line8.isEmpty()) {
      wmsOrder8.setLine(line8);
      wmsOrderService.insertByBo(wmsOrder8);
    }
    if (!line6.isEmpty()) {
      wmsOrder6.setLine(line6);
      wmsOrderService.insertByBo(wmsOrder6);
    }
    return toAjax(baseMapper.updateById(lead));
  }

  private WmsOrder createOrder(Long typeId,String name,HrpLead lead){
    WmsOrder wmsOrder = new WmsOrder();
    wmsOrder.setTypeId(typeId);
    wmsOrder.setName(name+lead.getName());
    wmsOrder.setPartnerId(lead.getPartnerId());
    wmsOrder.setStatus("1");
//    wmsOrder.setBackId(typeId + 1L); backId 指的是冲销的ID
    wmsOrder.setSourceId(lead.getId());
    wmsOrder.setApplicantId(lead.getCreateBy());
    wmsOrder.setRemark(name);
    return wmsOrder;
  }

  @Transactional(propagation = Propagation.REQUIRED)
  public WmsOrderLine generateOrder(HrpLeadQuote lead) {
    WmsOrderLine wmsOrderLine = new WmsOrderLine();
    wmsOrderLine.setProductId(lead.getProductId());
    wmsOrderLine.setBatchCode(lead.getBatchCode());
    wmsOrderLine.setMeasureUnit(lead.getMeasureUnit());
    wmsOrderLine.setQuantity(lead.getQuantity());
    wmsOrderLine.setTotalMoney(lead.getTotalMoney());
    wmsOrderLine.setDiscountMoney(lead.getDiscountMoney());
    wmsOrderLine.setCostMoney(lead.getCostMoney());
    wmsOrderLine.setPrice(lead.getPrice());
    return wmsOrderLine;
  }

  private LambdaQueryWrapper<WmsOrder> buildWmsOrderQueryWrapper(Long id) {
    LambdaQueryWrapper<WmsOrder> lqw = Wrappers.lambdaQuery();
    lqw.eq(id != null, WmsOrder::getSourceId, id);
    return lqw;
  }

  /**
   * 获取备注
   */
  public TableDataInfo<HrpLeadComment> getCommentById(Long id){
    return TableDataInfo.build(commentMapper.selectListById(id));
  }

  /**
   * 获取订单
   */
  public TableDataInfo<HrpLeadQuote> getQuoteById(Long id){
    return TableDataInfo.build(quoteMapper.selectListById(id));
  }

  //添加评论跟踪
  @Transactional(propagation = Propagation.REQUIRED)
  public void saveComment(HrpLead bo) {
    if (bo.getRemark() != null && !bo.getRemark().isEmpty()){
      HrpLeadComment hrpLeadComment = new HrpLeadComment();
      BeanUtils.copyProperties(bo,hrpLeadComment);
      hrpLeadComment.setCreateTime(DateTime.now());
      commentMapper.insert(hrpLeadComment);
    }
  }
  public WmsOrderLine mapToWmsOrderLine(HrpLeadQuote quote) {
    WmsOrderLine orderLine = new WmsOrderLine();
    orderLine.setProductId(quote.getProductId());
    orderLine.setBatchCode("0");
    orderLine.setMeasureUnit(quote.getMeasureUnit());
    orderLine.setPrice(quote.getPrice());
    orderLine.setQuantity(quote.getQuantity());
    orderLine.setTotalMoney(quote.getTotalMoney());
    orderLine.setDiscountMoney(quote.getDiscountMoney());
    orderLine.setCostMoney(quote.getCostMoney());
    return orderLine;
  }
}




